﻿using System.Security.Claims;
using log4net;
using Mathmall.Administration.Data;
using Mathmall.Administration.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace Mathmall.Administration.Mapper
{
    public class UserMapper : BaseMapper
    {
        private readonly UserManager<User> _userManager;

        public UserMapper(AdministrationContext context, UserManager<User> userManager
        ) : base(context)
        {
            _userManager = userManager;
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="user">用户信息</param>
        /// <returns></returns>
        public async Task<IdentityResult> AddUser(User user)
        {
            return await _userManager.CreateAsync(user);
        }

        /// <summary>
        /// 根据条件查询用户信息
        /// </summary>
        /// <returns></returns>
        public IQueryable<User> GetAllUsers()
        {
            return _userManager.Users;
        }

        /// <summary>
        /// 根据id查询用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<User> GetUserById(int userId)
        {
            return (await _context.Users.FindAsync(userId))!;
        }

        /// <summary>
        /// 根据id集合批量删除用户角色信息
        /// </summary>
        /// <param name="userIds"></param>
        /// <returns></returns>
        public async Task<int> DeleteUserRole(List<int> userIds)
        {
            return await _context.UserRoles.Where(userRole => userIds.Contains(userRole.UserId)).ExecuteDeleteAsync();
        }

        /// <summary>
        /// 根据用户id集合批量删除用户
        /// </summary>
        /// <param name="userIds"></param>
        /// <returns></returns>
        public async Task<int> DeleteUsersByUserIds(List<int> userIds)
        {
            return await _context.Users.Where(user => userIds.Contains(user.Id)).ExecuteDeleteAsync();
        }

        /// <summary>
        /// 查询用户信息
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task<User?> Select(string username, string password)
        {
            var user = await _context.Users
                .AsNoTracking()
                .SingleOrDefaultAsync(u => u.UserName == username && u.PasswordHash == password);
            return user;
        }

        /// <summary>
        /// 根据用户id查询角色id
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<List<int>> GetRoleIdsByUserId(int userId)
        {
            IQueryable<int> roleIds = from userRole in _context.UserRoles
                where userRole.UserId == userId
                select userRole.RoleId;
            return await roleIds.ToListAsync();
        }

        /// <summary>
        /// 查询用户的菜单
        /// </summary>
        /// <param name="roleIds"></param>
        /// <returns></returns>
        public async Task<List<Menu>> GetMenusByRoleId(List<int> roleIds)
        {
            // 查询用户的权限
            IQueryable<int> menuIDs = from roleMenu in _context.RoleMenu
                join menu in _context.Menus on roleMenu.MenuId equals menu.MenuID
                where roleIds.Contains(roleMenu.RoleId)
                select menu.MenuID;

            var ints = await menuIDs.ToArrayAsync();

            string a = "(";
            foreach (int i in ints)
            {
                a += " " + i + ",";
            }

            a += ")";
            a = a.Replace(",)", ")");

            // 查询用户权限的父id，方便在前端展示
            string sql = $"with Recursive as (select * from dbo.Menu where MenuID in " + a +
                         " union all select c.* from dbo.Menu as c inner join Recursive as rc on c.MenuID = rc.ParentId) select * from Recursive;";

            return await _context.Menus.FromSqlRaw(sql).ToListAsync();
        }
    }
}